# api/users.py
"""
Author: didiplus
Description: 用户相关API
Date: 2025-08-20 21:00:00
LastEditors: didiplus
LastEditTime: 2025-08-20 21:00:00
FilePath: /WeChatBot/app/api/users.py
Version: 1.0
"""
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List

# 使用相对导入方式引入模块
from core.database import get_db
from schemas.user import User, UserUpdate
from services.user import UserService
from api.deps import get_current_active_user
11
router = APIRouter()

@router.get("/me", response_model=User)
def read_users_me(current_user: User = Depends(get_current_active_user)):
    """
    获取当前登录用户的信息
    """
    return current_user

@router.get("/", response_model=List[User])
def read_users(
    skip: int = 0, 
    limit: int = 100, 
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取用户列表（仅超级用户可访问）
    """
    # 检查是否为超级用户
    if not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="仅超级用户可访问用户列表"
        )
    
    user_service = UserService(db)
    users = user_service.get_users(skip=skip, limit=limit)
    return users

@router.get("/{user_id}", response_model=User)
def read_user(
    user_id: int, 
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    根据ID获取用户信息
    普通用户只能获取自己的信息，超级用户可以获取任何用户信息
    """
    # 检查权限：普通用户只能查看自己的信息
    if not current_user.is_superuser and current_user.id != user_id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权限访问其他用户信息"
        )
    
    user_service = UserService(db)
    db_user = user_service.get_user_by_id(user_id=user_id)
    if not db_user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return db_user

@router.put("/{user_id}", response_model=User)
def update_user(
    user_id: int, 
    user_update: UserUpdate, 
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    更新用户信息
    普通用户只能更新自己的信息，超级用户可以更新任何用户信息
    """
    # 检查权限：普通用户只能更新自己的信息
    if not current_user.is_superuser and current_user.id != user_id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权限更新其他用户信息"
        )
    
    user_service = UserService(db)
    try:
        db_user = user_service.update_user(user_id=user_id, user_update=user_update)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    
    if not db_user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return db_user

@router.delete("/{user_id}")
def delete_user(
    user_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    删除用户（软删除）
    普通用户不能删除用户，仅超级用户可以删除用户
    """
    # 检查权限：仅超级用户可以删除用户
    if not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权限删除用户"
        )
    
    # 不允许用户删除自己
    if current_user.id == user_id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="不能删除自己的账户"
        )
    
    user_service = UserService(db)
    success = user_service.delete_user(user_id=user_id)
    if not success:
        raise HTTPException(status_code=404, detail="用户不存在")
    return {"message": "用户删除成功"}